<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Table</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      :root {
        --primary: #00b0f0;
      }

      button {
        padding: 2px 6px;
      }

      .container {
        margin: 60px auto 0;
        width: 60%;
      }

      .table {
        display: flex;
        flex-direction: column;
        width: 1005;
      }

      .row {
        display: flex;
      }

      .row div {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 80px;
        height: 30px;
        border: 1px solid #000;
      }

      .row:not(:nth-child(1)) div {
        border-top: none;
        border-left: none;
      }

      .row:not(:nth-child(1)) div:nth-child(1) {
        border-left: 1px solid #000;
      }

      .table-header div {
        background-color: var(--primary);
        color: #fff;
        font-weight: 700;
        border-left: none;
      }

      .table-header .checkall {
        display: flex;
        cursor: pointer;
        user-select: none;
      }

      .table-header div:nth-child(1) {
        border-left: 1px solid #000;
      }
      .options {
        display: flex;
        margin-top: 8px;
      }

      .options div {
        margin-right: 16px;
        text-decoration: underline;
        color: var(--primary);
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="table">
        <div class="row table-header">
          <div class="checkall">
            <input type="checkbox" id="checkall" />
            <label for="checkall">全选</label>
          </div>
          <div>商品信息</div>
          <div>价格</div>
          <div>数量</div>
          <div>操作</div>
        </div>
      </div>
      <div class="options">
        <div class="mass-deletion">批量删除</div>
        <div class="add-row">增加新数据</div>
      </div>
    </div>

    <script>
      $(() => {
        let data = [
          {
            id: 1,
            goodName: "1111",
            price: "￥2999",
            quantity: "50",
            checked: false,
          },
          {
            id: 2,
            goodName: "222",
            price: "￥1999",
            quantity: "50",
            checked: true,
          },
        ]

        const randomString = (len) => {
          len = len || 32
          var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
          var maxPos = $chars.length
          var pwd = ""
          for (i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
          }
          return pwd
        }

        function randomNum(minNum, maxNum) {
          switch (arguments.length) {
            case 1:
              return parseInt(Math.random() * minNum + 1, 10)
              break
            case 2:
              return parseInt(
                Math.random() * (maxNum - minNum + 1) + minNum,
                10
              )
              break
            default:
              return 0
              break
          }
        }

        const createRowElement = (item) =>
          $(` <div class="row" data-id="${item.id}">
                  <div><input class="check-row" type="checkbox" ${
                    item.checked && "checked"
                  }/></div>
                  <div>${item.goodName}</div>
                  <div>${item.price}</div>
                  <div>${item.quantity}</div>
                  <div><button class="del">删除</button></div>
                </div>`)

        const render = () => {
          $(".table .row").not(".table-header").remove()
          if (data.length) {
            data.forEach((item) => {
              const row = createRowElement(item)
              $(".table-header").after(row)
            })
          }
          listenToDelRow()
          handleCheckRow()
        }

        const listenToDelRow = () => {
          $(".del").on("click", function () {
            const goodId = $(this).parent().parent().attr("data-id")
            data = data.filter((item) => item.id !== parseInt(goodId))
            render()
          })
        }

        const handleCheckRow = () => {
          $(".check-row").click(function () {
            const currentId = parseInt(
              $(this).parent().parent().attr("data-id")
            )
            data.forEach((item) => {
              if (item.id === currentId) {
                item.checked = !item.checked
              }
            })
          })
        }

        const handleCheckAll = () => {
          $(".checkall").click(function (e) {
            e.preventDefault()
            const checkedData = data.filter((item) => item.checked === true)
            const willCheck = checkedData.length === data.length ? false : true
            willCheck === true
              ? $(".checkall input").attr("checked", "checked")
              : $(".checkall input").removeAttr("checked")

            data.forEach((item) => {
              item.checked = willCheck
            })
            render()
          })
        }

        const handleMassDeletion = () => {
          $(".mass-deletion").click(function () {
            data = data.filter((item) => item.checked === false)
            render()
          })
        }

        const addNewRow = () => {
          $(".add-row").click(function () {
            const id = new Date().getTime()
            const goodName = randomString(5)
            const price = `￥${randomNum(1000, 3000)}`
            const quantity = randomNum(30, 100)
            data.push({
              id,
              goodName,
              price,
              quantity,
              checked: false,
            })
            console.log(data)
            render()
          })
        }

        ;(() => {
          render()

          handleCheckAll()
          handleMassDeletion()
          addNewRow()
        })()
      })
    </script>
  </body>
</html>
